<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/8/29
 * Time: 11:07
 */
namespace app\api\controller;
use think\Db;
class Online extends Base {
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $useridddd = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($useridddd,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    //学科分类
    public function itemize(){
        $res = Db::table('up_subject')->order('subject_sort asc')->select();
        return json(['status' => 200, 'msg' => $res]);
    }

    //在线老师
    public function teacher(){
        $page = input('param.page')?input('param.page'):1;
        $subject_id = input('param.subject_id');
        $num = 10;
        $limit = $page-1;
        $where['user_subject'] = $subject_id;
        $where['user_type'] = 2;
        $where['user_status'] = 2;
        $where['user_online'] = 1;
        
        // 用户年级条件
        $user_id = input('user_id');
        $user_info = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_grade, user_subject')
            ->find();
        $small = [1,2,3,4,5,6];
        $middle = [7,8,9];
        $hight = [10,11,12];
        
        $res = Db::table('up_u_user')->where($where)
            ->where(function ($query) use ($user_info, $small, $middle, $hight){
                if(in_array($user_info['user_grade'], $small)){
                    $query->where('user_grade', 'IN', $small);
                }
                if(in_array($user_info['user_grade'], $middle)){
                    $query->where('user_grade', 'IN', $middle);
                }
                if(in_array($user_info['user_grade'], $hight)){
                    $query->where('user_grade', 'IN', $hight)
                        ->whereOr('user_subject', 10);
                }
            })
            ->field('user_image,user_intro,user_shi,user_grade,user_gender,user_id,
            user_username, user_tcahe_style,user_good_at')
            ->limit($num*$limit,$num)
            ->order('user_is_top asc, user_sort desc')
            ->select();
        foreach ($res as $key=>&$vo){
            //地区
            $address = Db::table('up_area')->where('district_id',$vo['user_shi'])->value('district');
            //星级
            $star = $this->teacherStar($vo['user_id']);
            //年级
            $grade = Db::table('up_grade')->where('grade_id',$vo['user_grade'])->value('grade_name');
            // 风格
            $style = Db::table('up_teach_style')
                ->where('style_id', $vo['user_tcahe_style'])
                ->value('style_name');
            $vo['teacher_style'] = $style;
            $vo['address'] = $address;
            $vo['star'] = $star;
            $vo['grade'] = $grade;
        }
        // 在线老师人数
        $teacher_num = Db::table('up_u_user')
            ->where('user_type', 2)
            ->where('user_status', 2)
            ->where('user_online', 1)
            ->count();
        return json(['status' => 200, 'msg' => $res, 'num' => $teacher_num]);
    }
     //提问
    public function question(){
        extract(input());
        $subject_id  = input('param.subject_id');
        $course_type  = input('param.course_type');
        $course_content  = input('param.course_content');
        $couse_img  = input('param.couse_img');
        $course_gold  = input('param.course_gold');
        $course_teacher_id  = input('param.course_teacher_id');
        $data['course_user_id'] = $user_id;
        $data['course_subject_id'] = $subject_id;
        $data['course_type'] = $course_type;
        if($course_type==1){
            $data['course_teacher_id'] = $course_teacher_id;
        }
        //查询这个用户的平台币
        $user_info = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_grade, user_balance')
            ->find();
        if($course_gold>$user_info['user_balance']){
            return  json(array('status'=>100,'msg'=>"平台币不足,请先充值"));
        }else{
            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_balance',$course_gold);
        }

        $data['course_content'] = $course_content;
        $data['couse_img'] = $couse_img;
        $data['course_gold'] = $course_gold;
        $data['course_time'] = date('Y-m-d H:i:s',time());
        $res = Db::table('up_course')->insertGetId($data);
        //插入购买记录表
        $data1['purchase_mony'] = $course_gold;
        $data1['purchase_user_id'] = $user_id;
        $data1['purchase_car_type'] = 1;
        $data1['purchase_type'] = 4;
        $data1['f_id'] = $res;
        $data1['purchase_target'] = 1;
        $data1['purchase_time'] = date('Y-m-d H:i:s',time());
        $data1['teacher_id'] = $course_teacher_id;
        Db::table('up_purchase')->insertGetId($data1);
        //插入订单表
        $data2['order_type']=2;
        $data2['order_price']=$course_gold;
        $data2['order_time']=date('Y-m-d H:i:s',time());
        $data2['order_user_id']=$user_id;
        Db::table('up_order')->insertGetId($data2);
        // 如果是指定老师，需要推送&插入消息表
        $list = [];
        if($course_type == 1){
            // 插入消息表
            allInNotice('指定求助', '您有学生求助，请及时登录回答！', 2, 2, 9, $res, $course_teacher_id);
            
            // 推送的数组
            $val = (string)$course_teacher_id;
            array_push($list, $val);
            $title = '指定求助';
        }else{ // 如果是未指定老师
            // 所有在线、审核通过、同学科、同年级的老师
            $teacherList = Db::table('up_u_user')
                ->where('user_type', 2)
                ->where('user_online', 1)
                ->where('user_status', 2)
                ->where('user_grade', $user_info['user_grade'])
                ->where('user_subject', $subject_id)
                ->field('user_id')
                ->select();
            
            foreach($teacherList as $k => $v){
                // 插入消息表
                allInNotice('公开求助', '有学生在线提问，请及时登录回答！', 2, 2, 9, $res, $v['user_id']);
                // 组装推送数组
                $val = (string)$v['user_id'];
                array_push($list, $val);
            }
            $title = '公开求助';
        }
        try{
            $this->JpushT(1, $list, $title, ['course_id' => $res, 'send_type' => 6]);
        }catch(\Exception $e){
        
        }
        if($res){
            return  json(array('status'=>200,'msg'=>"发布成功"));
        }else{
            return  json(array('status'=>100,'msg'=>"发布失败"));
        }
    }

    //选择老师
    public function selectTeacher(){
        $page = input('param.page')?input('param.page'):1;
        $keyword = trim(input('keyword'), ' ');
        $num = 10;
        $limit = $page-1;
        $where['user_type'] = 2;
        $where['user_status'] = 2;
        $where['user_online'] = 1;
        if(!empty($keyword)){
            $where['user_username|userid|district'] = array('like',"%$keyword%");
        }
        $where['user_subject'] = input('param.user_subject');
        $res = Db::table('up_u_user')->alias('u')
            ->join('up_area a','u.user_shi=a.district_id','left')
            ->where($where)
            ->field('user_id,user_username')
            ->limit($num*$limit,$num)
            ->select();
        return  json(array('status'=>200,'msg'=>$res));
    }

    //搜索老师
    public function keywordTeacher(){
        $page = input('param.page')?input('param.page'):1;
        $keyword = input('param.keyword');
        $res = array();
        if($keyword==''){
            return  json(array('status'=>200,'msg'=>$res));
        }
        $num = 10;
        $limit = $page-1;
        $where['user_type'] = 2;
        $where['user_status'] = 2;
        $where['user_username|userid|district'] = array('like',"%$keyword%");
        $res = Db::table('up_u_user')->alias('u')
            ->join('up_area a','u.user_shi=a.district_id','left')
            ->where($where)
            ->field('user_image,user_online,user_intro,user_shi,user_grade,user_gender,
            user_id,user_username,user_learn_status, user_tcahe_style,user_good_at')
            ->limit($num*$limit,$num)
            ->order('user_is_top asc, user_sort desc')
            ->select();
        foreach ($res as $key=>&$vo){
            //地区
            $address = Db::table('up_area')->where('district_id',$vo['user_shi'])->value('district');
            //星级
            $star = $this->teacherStar($vo['user_id']);
            //年级
            $grade = Db::table('up_grade')->where('grade_id',$vo['user_grade'])->value('grade_name');
            // 风格
            $style = Db::table('up_teach_style')
                ->where('style_id', $vo['user_tcahe_style'])
                ->value('style_name');
            $vo['teacher_style'] = $style;
            $vo['address'] = $address;
            $vo['star'] = $star;
            $vo['grade'] = $grade;
        }
        return  json(array('status'=>200,'msg'=>$res));
    }

    //一对一老师
    public function oneTeacher(){
        $page = input('param.page')?input('param.page'):1;
        $subject_id = input('param.subject_id');
        $num = 10;
        $limit = $page-1;
        $where['user_subject'] = $subject_id;
        $where['user_type'] = 2;
        $where['user_status'] = 2;
        $where['user_out'] = 1;
        $where['user_online'] = 1;
        // 用户年级条件
        $user_id = input('user_id');
        $user_info = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_grade, user_subject')
            ->find();
        $small = [1,2,3,4,5,6];
        $middle = [7,8,9];
        $hight = [10,11,12];
        $res = Db::table('up_u_user')->where($where)
            ->where(function ($query) use ($user_info, $small, $middle, $hight){
                if(in_array($user_info['user_grade'], $small)){
                    $query->where('user_grade', 'IN', $small);
                }
                if(in_array($user_info['user_grade'], $middle)){
                    $query->where('user_grade', 'IN', $middle);
                }
                if(in_array($user_info['user_grade'], $hight)){
                    $query->where('user_grade', 'IN', $hight)
                        ->whereOr('user_subject', 10);
                }
            })
            ->field('user_learn_status,user_image,user_intro,user_sheng,user_grade,
            user_gender,user_id,user_username,user_learn_status, user_tcahe_style,user_good_at')
            ->limit($num*$limit,$num)
            ->order('user_is_top asc, user_sort desc')
            ->select();
        foreach ($res as $key=>&$vo){
            //地区
            $address = Db::table('up_area')->where('district_id',$vo['user_sheng'])->value('district');
            //星级
            $star = $this->teacherStar($vo['user_id']);
            //年级
            $grade = Db::table('up_grade')->where('grade_id',$vo['user_grade'])->value('grade_name');
            // 风格
            $style = Db::table('up_teach_style')
                ->where('style_id', $vo['user_tcahe_style'])
                ->value('style_name');
            $vo['teacher_style'] = $style;
            $vo['address'] = $address;
            $vo['star'] = $star;
            $vo['grade'] = $grade;
            $res[$key]['user_learn_status'] = 1;
            $have = Db::table('up_one_to_one')
                ->where('one_teacher_id',$vo['user_id'])
                ->where('one_status','in','3,2')
                ->find();
            if($have){
                $res[$key]['user_learn_status'] = 2;
            }
        }
        return json(['status' => 200, 'msg' => $res]);
    }

    //老师详情
    public function teacherDetail(){
        extract(input());
        $id = input('param.id');
        $where['user_id'] = $id;
        $res = Db::table('up_u_user')->where($where)
            ->field('userid,user_image,user_intro,user_shi,user_grade,user_gender,
            user_id,user_username,user_learn_status,user_good_at,
            user_exper,user_honor_img,user_toll,user_tcahe_style,user_subject,user_online,user_learn_status')
            ->find();
        $map['follow_user_id'] = $user_id;
        $map['follow_quilt_user_id'] = $id;
        $info = Db::table('up_follow_user')->where($map)->find();
        if($info['follow_id']!=''){
            $res['is_dz'] = 1;
        }else{
            $res['is_dz'] = 2;
        }
        //查询自己是否申请
        $where1['one_student_id'] = $user_id;
//        $where1['one_teacher_id'] = $id;
        $where1['one_status'] = array('IN',array(1,2,3));
        $info1 = Db::table('up_one_to_one')->where($where1)->find();
        if($info1['one_id']!=''){
            $res['is_class'] = 1;
        }else{
            $res['is_class'] = 2;
        }
        //地区
        $address = Db::table('up_area')->where('district_id',$res['user_shi'])->value('district');
        //星级
        $star = $this->teacherStar($res['user_id']);
        //年级
        $grade = Db::table('up_grade')->where('grade_id',$res['user_grade'])->value('grade_name');
        //教学特色
        $style_name = Db::table('up_teach_style')->where('style_id',$res['user_tcahe_style'])->value('style_name');
        //科目
        $subject_name = Db::table('up_subject')->where('subject_id',$res['user_subject'])->value('subject_name');
        $res['star'] = $star;
        $res['address'] = $address;
        $res['grade'] = $grade;
        $res['style_name'] = $style_name;
        $res['subject_name'] = $subject_name;
        //---------------
        $res['user_learn_status'] = 1;
        $have = Db::table('up_one_to_one')
            ->where('one_teacher_id',$id)
            ->where('one_status','in','3,2')
            ->find();
        if($have){
            $res['user_learn_status'] = 2;
        }
        //---------------
        return json(['status' => 200, 'msg' => $res]);
    }
    //关注，取消关注
    public function like(){
        extract(input());
        $id = input('param.id');
        $map['follow_user_id'] = $user_id;
        $map['follow_quilt_user_id'] = $id;
        $info = Db::table('up_follow_user')->where($map)->find();
        if($info['follow_id']!=''){
            $res = Db::table('up_follow_user')->where($map)->delete();
            if($res){
                return  json(array('status'=>200,'msg'=>"取消成功"));
            }else{
                return  json(array('status'=>200,'msg'=>"取消失败"));
            }
        }else{
            $res = Db::table('up_follow_user')->insertGetId($map);
            if($res){
                return  json(array('status'=>200,'msg'=>"点赞成功"));
            }else{
                return  json(array('status'=>200,'msg'=>"点赞失败"));
            }
        }
    }
    //我要上课
    public function classes(){
        extract(input());
        $id = input('param.id');


        $where['one_student_id'] = $user_id;
//        $where['one_teacher_id'] = $id;
//        $where['one_subject_id'] = input('param.one_subject_id');
        $where['one_status'] = array('not in',array(4,5,6));
        $info = Db::table('up_one_to_one')->where($where)->find();
        if($info['one_id']!=''){
            return  json(array('status'=>100,'msg'=>"已经申请了不能重复申请"));
        }

        $where1['one_teacher_id'] = $id;
        $where1['one_status'] = array('IN',array(2,3));
        $info1 = Db::table('up_one_to_one')->where($where)->find();
        if($info1['one_id']!=''){
            return  json(array('status'=>100,'msg'=>"该老师正在有课,不能重复申请"));
        }
        //查询这个老师的收费标准
//        $user_out = Db::table('up_u_user')->where('user_id',$id)->value('user_out');
//        if($user_out != 1){
//            return  json(array('status'=>100,'msg'=>"该老师一对一没有在线，请稍等~"));
//        }
        $user_toll = Db::table('up_u_user')->where('user_id',$id)->value('user_toll');
        $user_balance = Db::table('up_u_user')->where('user_id',$user_id)->value('user_balance');
        //判断这个收费金额是否大于用户的金额
        if($user_toll>$user_balance){
            return  json(array('status'=>100,'msg'=>"平台币不足,请先充值"));
        }else{
            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_balance',$user_toll);
        }

        $data['one_student_id'] = $user_id;
        $data['one_teacher_id'] = $id;
        $data['one_subject_id'] = input('param.one_subject_id');
        $data['one_time'] = date('Y-m-d H:i:s',time());
        $res = Db::table('up_one_to_one')->insertGetId($data);

        //插入订单表
        $data1['order_type'] = 3;
        $data1['order_price'] = $user_toll;
        $data1['order_time'] = date('Y-m-d H:i:s',time());
        $data1['order_user_id'] = $user_id;
        Db::table('up_order')->insertGetId($data1);


        //插入购买记录表
        $data2['purchase_mony'] = $user_toll;
        $data2['purchase_user_id'] = $user_id;
        $data2['purchase_car_type'] = 1;
        $data2['purchase_type'] = 3;
        $data2['f_id'] = $res;
        $data2['purchase_target'] = 1;
        $data2['purchase_time'] = date('Y-m-d H:i:s',time());
        $data2['teacher_id'] = $id;
        Db::table('up_purchase')->insertGetId($data2);
        // 消息表
        allInNotice('一对一辅导申请动态', '有学生完成了一对一辅导的支付，快去上课吧~', 2, 2, 7, -1, $id);
        // 极光推送
        $list = [];
        $val = (string)$id;
        array_push($list, $val);
        try{
            $this->JpushT(1, $list, '一对一辅导申请动态', ['send_type' => 4]);
        }catch(\Exception $e){
        
        }
//        Db::table('up_u_user')->where('user_id',input('param.teacher_id'))->setField('user_learn_status',2);
        if($res){
            return  json(array('status'=>200,'msg'=>"申请成功"));
        }else{
            return  json(array('status'=>100,'msg'=>"申请失败"));
        }
    }
     //确认支付
    public function affirm(){
//        extract(input());
//        $id = input('param.id');
//        $money = input('param.money');
//        $user_balance = Db::table('up_u_user')->where('user_id',$user_id)->value('user_balance');
//        if($money>$user_balance){
//            return  json(array('status'=>100,'msg'=>"平台币不足,请先充值"));
//        }else{
//            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_balance',$money);
//        }
//        //插入订单表
//        $data1['order_type'] = 3;
//        $data1['order_price'] = $money;
//        $data1['order_time'] = date('Y-m-d H:i:s',time());
//        $data1['order_user_id'] = $user_id;
//        Db::table('up_order')->insertGetId($data1);
//
//        //插入购买记录表
//        $data2['purchase_mony'] = $money;
//        $data2['purchase_user_id'] = $user_id;
//        $data2['purchase_car_type'] = 1;
//        $data2['purchase_type'] = 3;
//        $data2['f_id'] = $id;
//        $data2['purchase_target'] = 1;
//        $data2['purchase_time'] = date('Y-m-d H:i:s',time());
//        Db::table('up_purchase')->insertGetId($data2);
//        return  json(array('status'=>200,'msg'=>"购买成功"));
    }
    //申请
    public function apply(){
        extract(input());
        $page = input('param.page')?input('param.page'):1;
        $num = 10;
        $limit = $page-1;
        $where['one_student_id'] = $user_id;
        $res = Db::table('up_one_to_one')->alias('a')
            ->join('up_u_user uuu','uuu.user_id = a.one_teacher_id','left')
            ->field('uuu.user_username,a.*')
            ->where($where)
            ->limit($num*$limit,$num)
            ->order('one_time desc')
            ->select();
        
        return  json(array('status'=>200,'msg'=>$res));
    }

    /**
     * 学生发起的连接
     * 待上课（连接老师上课传3）
     * @return \think\response\Json
     */
    public function applyChangeStatus(){
        extract(input());
        $update = array();
        $data = Db::table('up_one_to_one')
            ->where('one_id',$one_id)
            ->find();
        if($type != 3){
            return  json(array('status'=>100,'msg'=>'非法请求'));
        }
        if($type == 3){
            if($data['one_status'] != 2){
                return  json(array('status'=>100,'msg'=>'只有待上课的才可以连接'));
            }
            $update['one_class_time'] = date('Y-m-d H:i:s');
        }
        $update['one_status'] = $type;
        $res = Db::table('up_one_to_one')->where('one_id',$one_id)->update($update);
        if($res){
            return  json(array('status'=>200,'msg'=>'操作成功'));
        }else{
            return  json(array('status'=>100,'msg'=>'操作失败'));
        }
    }

    //公开课
    public function classed(){
        $page = input('param.page')?input('param.page'):1;
        $num = 10;
        $limit = $page-1;
        $id= input('param.id');
        $where['public_teacher_id'] = $id;
        $where['public_is_on'] = 1;
        $res = Db::table('up_public_class')->where($where)
            ->limit($num*$limit,$num)
            ->select();
        foreach ($res as $key=>&$vo){
           $count = Db::table('up_public_apply')->where('apply_public_id',$vo['public_id'])->count();
            $vo['num'] = $count;
        }
        return  json(array('status'=>200,'msg'=>$res));
    }

    public function report(){
        extract(input());
        $id = input('param.id');
        $content = 2;
        $one_tousu_reason= input('param.one_tousu_reason');
        $data['one_tousu'] = $content;
        $data['one_tousu_reason'] = $one_tousu_reason;
        Db::table('up_one_to_one')->where('one_id',$id)->update($data);
        return  json(array('status'=>200,'msg'=>"申请成功"));
    }

    /**
     * 专为前端：学生连接时判断这个课程有没有结束
     * @return \think\response\Json
     */
    public function OnetoOneOver(){
        extract(input());
        $update = array();
        $data = Db::table('up_one_to_one')
            ->where('one_id',$one_id)
            ->find();
        if(!$data){
            return  json(array('status'=>100,'msg'=>'无此课程'));
        }else{
            if($data['one_status'] == 2 || $data['one_status'] == 3){
                return  json(array('status'=>200,'msg'=>'ok'));
            }else{
                return  json(array('status'=>100,'msg'=>'此课程已结束'));
            }
        }

    }
    
    /**
     * 用于更新上课剩余时间
     */
    public function updateClassTime(){
        $one_id = input('one_id');
        $class_time = input('class_time');
        // 防止负数的情况出现
        $second = Db::table('up_one_to_one')->where('one_id', $one_id)->value('one_second');
        if($second <= $class_time){
            Db::table('up_one_to_one')->where('one_id', $one_id)->setField('one_second', 0);
        }else{
            Db::table('up_one_to_one')->where('one_id', $one_id)->setDec('one_second', $class_time);
        }
        return json(['status' => 200, 'msg' => 'ok']);
    }
}